package com.example.fw;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.GroupObject;

public class GroupHelper extends HelperWithWebDriverBase {

	public GroupHelper(AppManager manager) {
		super(manager);
	}

	public Set<GroupObject> getGroups() {
		manager.getNavigationHelper().goToGroupListPage();
		WebElement form = findElements(By.tagName("form")).get(1);
		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
		Set<GroupObject> groups = new HashSet<GroupObject>();
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			//
			title = title.substring("Select (".length(),
					title.length() - ")".length());
			//
			GroupObject group = new GroupObject().setName(title).setId(
					checkbox.getAttribute("value"));
			groups.add(group);
		}

		return groups;
	}

	public void createGroup(GroupObject groupObject) {
		manager.getNavigationHelper().goToGroupListPage();
		initGroupCreation();
		fillGroupForm(groupObject);
		submitFilledFormCreation();
		manager.getNavigationHelper().returnToGroupListPage();
	}

	public void deleteGroup(int i) {
		manager.getNavigationHelper().goToGroupListPage();
		chekGroup(i);
		click(By.name("delete"));
		manager.getNavigationHelper().returnToGroupListPage();
	}

	private void chekGroup(int i) {
		click(By.name("selected[]"));
	}

	public void modeGroup(int i, GroupObject addGroup) {
		manager.getNavigationHelper().goToGroupListPage();
		initGroupMode(i);
		fillGroupForm(addGroup);
		submitFormMode();
		manager.getNavigationHelper().returnToGroupListPage();
	}

	private void submitFormMode() {
		click(By.name("update"));
	}

	private void initGroupMode(int i) {
		chekGroup(i);
		click(By.name("edit"));
	}

	private void fillGroupForm(GroupObject groupObject) {
		type(By.name("group_name"), groupObject.name);
		type(By.name("group_header"), groupObject.header);
		type(By.name("group_footer"), groupObject.footer);
	}

	private void initGroupCreation() {
		findElement(By.name("new")).click();
	}
}
